<template>
    <div class="form__container">
        <n-form ref="formRef" :model="form" :rules="rules" label-placement="left" label-align="right" label-width="120"
            require-mark-placement="right-hanging">
            <n-grid :cols="24" :x-gap="24">
                <n-form-item-gi :span="12" label="抽签赛制" path="gameMode">
                    {{ computedGameMode(form.gameMode) }}
                </n-form-item-gi>
                <n-form-item-gi :span="12" label="抽签模式" path="extractMode">
                    {{ computedExtractMode(form.extractMode) }}
                </n-form-item-gi>
                <n-form-item-gi :span="24" label="抽取标题" path="extractLabel">
                    <n-input v-model:value="form.extractLabel" :readonly="props.readOnly" placeholder="请输入抽取标题" />
                </n-form-item-gi>
                <n-form-item-gi :span="12" label="抽签人" path="extractPerson">
                    <n-input v-model:value="form.extractPerson" readonly placeholder="请输入抽签人" />
                </n-form-item-gi>
                <n-form-item-gi :span="12" label="抽签人qq号" path="qqNumber">
                    <n-input v-model:value="form.qqNumber" readonly placeholder="请输入qq号" />
                </n-form-item-gi>
                <n-form-item-gi :span="12" label="抽取战队数量" path="extractNumber">
                    <n-input-number :min="0" :max="256" v-model:value="form.extractNumber" :readonly="props.readOnly"
                        placeholder="请输入战队数量" />
                </n-form-item-gi>
                <n-form-item-gi :span="12" label="分组数量" path="groupNumber">
                    <n-input-group>
                        <n-input-number :min="1" v-model:value="form.groupNumber" :step="1"
                            :readonly="props.readOnly || form.gameMode === 'Elimi'" placeholder="请输入分组数量"
                            :style="{ width: '60%' }" />
                        <n-input v-model:value="groupEvenryPerson" disabled :style="{ width: '40%' }" />
                    </n-input-group>
                </n-form-item-gi>
                <n-form-item-gi :span="24" label="添加战队" v-if="!readOnly">
                    <n-input-group>
                        <n-input v-model:value="teamName" :style="{ width: '40%' }" placeholder="请输入战队名" />
                        <n-button type="primary" ghost @click="addOneTeam">
                            单个添加
                        </n-button>
                        <n-button type="info" @click="showModal = true">
                            全局导入
                        </n-button>
                    </n-input-group>
                </n-form-item-gi>
                <n-form-item-gi :span="24" label="队伍名单">
                    <n-empty v-if="teamList.length === 0" description="未登记任何队伍">
                    </n-empty>
                    <div class="team__list--container" v-else>
                        <n-tag style="min-width:120px;" type="info" :closable="!readOnly" v-for="item in teamList"
                            :key="item" @close="handleMinusTeam(item)">
                            {{ item }}
                        </n-tag>
                    </div>
                </n-form-item-gi>
            </n-grid>
        </n-form>
    </div>
    <n-modal v-model:show="showModal">
        <n-card style="width: 600px" title="全局导入" :bordered="false" size="huge" role="dialog" aria-modal="true">
            <n-input v-model:value="allInputTeams" type="textarea" placeholder="请输入战队集群，用中文顿号隔开，例如：ASG1、ASG2" />
            <template #footer>
                <n-button type="warning" @click="handleImport">导入</n-button>
            </template>
        </n-card>
    </n-modal>
    <preNextButton v-if="!readOnly" :validateFunction="validator" :nowProcess="props.nowProcess"
        revokeWarningText="您确定返回到第一步重新选择赛制吗？一旦确定，所填写表单信息将全部清除。" @nextClick="handleNext" @preClick="handlePre">
    </preNextButton>
</template>

<script setup lang='ts'>
import { useDialog, useMessage, type FormInst, type FormItemRule } from 'naive-ui';
import { useUserStore } from '@/stores/user';
const emits = defineEmits(['nextClick', 'preClick', 'updateTeam']);
const message = useMessage();
const userStore = useUserStore();
const dialog = useDialog()
const props = defineProps({
    nowProcess: {
        type: Number,
        required: true
    },
    extractObject: {
        type: Object,
        required: true
    },
    readOnly: {
        type: Boolean,
        required: true
    }
});
interface ExtractOptions {
    extractLabel: string | null //抽取标题
    extractNumber: number | null //抽取人数
    groupNumber: number | null //分组
    extractPerson: string | null //抽签人
    qqNumber: string | null //qq号
    gameMode: 'Group' | 'Elimi' | 'Ring' | null
    extractMode: 'Card' | 'Ballot' | null
}
const formRef = ref<FormInst | null>(null);
const form = reactive<ExtractOptions>({
    extractLabel: null,
    extractNumber: null,
    groupNumber: null,
    extractPerson: null,
    gameMode: null,
    qqNumber: null,
    extractMode: null
})
const teamName = ref('');
const teamList = reactive<string[]>([]);
const showModal = ref(false);
const allInputTeams = ref('');

watch(() => form.extractNumber, (newVal) => {
    if (form.gameMode === 'Elimi' && newVal) {
        form.groupNumber = Math.ceil(newVal / 2);
    }
})
const rules = {
    gameMode: {
        required: true,
        message: '请选择游戏赛制',
        trigger: ['input', 'blur']
    },
    extractMode: {
        required: true,
        message: '请选择抽签模式',
        trigger: ['input', 'blur']
    },
    extractLabel: {
        required: true,
        message: '请输入抽取标题',
        trigger: ['input', 'blur']
    },
    extractNumber: {
        required: true,
        message: '请输入抽取战队数量',
        trigger: 'blur',
        validator(rule: FormItemRule, value: number) {
            console.log(rule);
            return value !== undefined && value !== null && value > 0;
        },
    },
    groupNumber: {
        required: true,
        message: '请输入组数',
        trigger: 'blur',
        validator(rule: FormItemRule, value: number) {
            console.log(rule);
            return value !== undefined && value !== null && value > 0;
        },
    }
}
// 全局导入
const handleImport = () => {
    dialog.warning({
        title: '警告',
        content: '你确定导入吗？之前手动添加的队伍将被覆盖',
        positiveText: '确定',
        negativeText: '不确定',
        draggable: true,
        onPositiveClick: () => {
                teamList.length = 0;
                const allTeams = allInputTeams.value.split('、');
                allTeams.forEach(item => {
                    teamList.push(item);
                })
                showModal.value = false;
        }
    })
}
// 添加一个队伍
const addOneTeam = () => {
    if (!teamName.value) return message.error('请输入队伍名称');
    if (teamList.includes(teamName.value)) return message.error(`${teamName.value}已存在！`);
    teamList.push(teamName.value);
    teamName.value = '';
}
// 删除队伍
const handleMinusTeam = (team: string) => {
    const index = teamList.indexOf(team);
    if (index !== -1) {
        teamList.splice(index, 1);
    } else {
        return false;
    }
}
const groupEvenryPerson = computed(() => {
    if (!form.extractNumber || !form.groupNumber) {
        return '自动计算';
    }
    if (form.extractNumber < form.groupNumber) {
        return '队数不够一组';
    }
    const every = Math.floor(form.extractNumber / form.groupNumber);
    return `每组 ${every} 队`
})
const init = () => {
    Object.assign(
        form,
        (props.extractObject?.options ?? {}),
        {
            extractMode: props.extractObject?.extractMode,
            gameMode: props.extractObject?.gameMode,
            extractPerson: userStore.userInfo.chinaname,
            qqNumber: userStore.userInfo.qqnumber
        });
    if (props.extractObject.data && props.extractObject.data.length > 0) {
        props.extractObject.data.forEach((item: string) => {
            teamList.push(item);
        })
    }
}
init();

const validator = async (): Promise<ReturnValidator> => {
    try {
        await formRef.value?.validate();
        if (form.extractNumber === 0 || form.extractNumber === null) {
            return {
                flag: false,
                messageText: '请填写抽取战队数量'
            }
        }
        if (form.gameMode === 'Elimi' && form.extractNumber % 2 !== 0) {
            return {
                flag: false,
                messageText: '抽取战队数量必须大于0且是2的倍数'
            }
        }
        if (form.extractNumber !== teamList.length) {
            return {
                flag: false,
                messageText: '输入战队数量和实际登记战队总数不一致'
            }
        }
        return {
            flag: true,
            messageText: 'ok'
        }
    } catch (error) {
        return {
            flag: false,
            messageText: '请完整填写表单'
        }
    }
}
// 计算比赛模式
const computedGameMode = (mode: 'Group' | 'Elimi' | 'Ring' | null): string => {
    if (!mode) return '未选择比赛模式'
    const mapList = {
        'Group': '小组赛',
        'Elimi': '淘汰赛',
        'Ring': '擂台赛'
    };
    return mapList[mode];
}

const computedExtractMode = (mode: 'Card' | 'Ballot' | null): string => {
    if (!mode) return '未选择比赛模式'
    const mapList = {
        'Card': '翻牌抽取',
        'Ballot': '大转盘',
    };
    return mapList[mode];
}
const handleNext = () => {
    emits('updateTeam', teamList)
    emits('nextClick', form, 'options');
}
const handlePre = () => {
    emits('preClick', 'options');
}
</script>
<style scoped lang='scss'>
.form__container {
    background: rgba(255, 255, 255, 0.4);
    -webkit-backdrop-filter: blur(5px);
    backdrop-filter: blur(5px);
    padding: 2rem;
    border-radius: 1rem;

    .team__list--container {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 1rem;
    }
}
</style>